/*
Source : https://leetcode.com/problems/merge-intervals/
Author : nflush@outlook.com
Date   : 2016-07-22
*/

/*
56. Merge Intervals
 ?  

Question Editorial Solution  
 My Submissions 




?Total Accepted: 73881
?Total Submissions: 281180
?Difficulty: Hard



Given a collection of intervals, merge all overlapping intervals.

For example,
 Given [1,3],[2,6],[8,10],[15,18],
 return [1,6],[8,10],[15,18]. 



Subscribe to see which companies asked this question
*/

/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
class Solution {
private:
    static bool compare(Interval &a, Interval &b){
        return a.start < b.start;
    }
public:
    vector<Interval> merge(vector<Interval>& intervals) {
        vector<Interval> ret;
        if (intervals.size() == 0) return ret;
        std::sort(intervals.begin(), intervals.end(), compare);
        ret.push_back(intervals[0]);
        int j = 0;
        for (int i = 1; i < intervals.size(); i++){
            if(ret[j].end >= intervals[i].start){
                ret[j].end = max(intervals[i].end, ret[j].end);
            } else {
                ++j;
                ret.push_back(intervals[i]);
            }
        }
        return ret;
    }
};



